<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {
    private $tb_article_category = 'article_category';
    private $tb_product_category = 'product_category';
    private $tb_product_manufacturer= 'product_manufacturer';
    private $tb_lienhe = 'lienhe';
    private $tb_tintuc = 'article';
    private $tb_product = 'product';
    private $tb_quangcao = 'quangcao';
    private $tb_setting='setting';
    private $tb_slideshow= 'slideshow';
    private $tb_users= 'users';
    //phan trang
    private $base_url_trang = '#';
    private $total_rows = 100;
    private $per_page =10;// bang voi limit
    private $limit = 10;//bang voi perpage
    ///
    private $sochu=20;//chon so chua cat dua vao intro bai viet
    private $id='';
    /**
     * 
     * thay doi field trong file view cho dung voi bang hien = publish 
     */
    function __construct()
	{
		parent::__construct();
        $this->load->library('session');  
		$this->load->helper(array('form','text','chuyendoitv_helper','url'));
		//$this->lang->load('tank_auth'); 
        $this->load->model('Admin_model');
        $this->load->library(array('pagination','form_validation','security'));
        if($this->auth()){            
        }else redirect('dangnhap');
	}
    function auth(){
        if($this->session->userdata('logedin')){
            if($this->session->userdata('id')==1){
                $this->session->set_userdata('upanh',1);//nho bo khi hoan thanh
                return true;
            }
        }else{
            $this->session->set_userdata('auth','Bạn không có quyền truy cập');
            return false;
        } 
    }
	public function index(){
        redirect('admin/xuly/setting/list');
	}
    function ajax(){
        if(!empty($_POST)){
            $data = $this->security->xss_clean($_POST['data']);
        }
        $table= $this->security->xss_clean($this->uri->segment(3,0));//bang
        $field= $this->security->xss_clean($this->uri->segment(4,0));//truong cua bang
        $uri5= $this->security->xss_clean($this->uri->segment(5,0)) ;//id cua bai viet can thay doi
        $uri6= $this->security->xss_clean($this->uri->segment(6,0));//id cua div can change
        $data = array(
               $field => $data               
            );
        $this->db->where('id', $uri5);
        $this->db->update($table, $data); 
        echo '#'.$uri6; // echo gui id ve 
    }
    function ajax_field(){
        if(!empty($_POST)){
            $data = $this->security->xss_clean($_POST['data']);
        }
        $uri3= $this->uri->segment(3,0);
        $uri4= $this->uri->segment(4,0);//bang
        if(!empty($data)){
            switch ($uri3){
                case 'order':
                    $this->session->set_userdata('order',$data);
                    if($this->session->userdata('sapxep')){
                        if($this->session->userdata('sapxep')=='ASC'){
                        $this->session->set_userdata('sapxep','DESC');
                        }else  $this->session->set_userdata('sapxep','ASC');
                    }else  $this->session->set_userdata('sapxep','ASC');
                    break;
                case 'num':
                    $this->session->set_userdata('limit',$data);
                    break;
                case $uri3=='pub':     
                    $data = $this->security->xss_clean($_POST);
                    $id=$data['id'];
                    $pulish =$data['publish']; 
                    $tba= $this->uri->segment(4,0);  
                    $this->db->where('id', $id);
                    $this->db->update($tba, array('publish'=>$pulish));
                    break;   
                case 'where':
                    if($uri4='article'){
                        switch ($data){
                            case 'all':
                                $this->session->set_userdata('all_article',1);
                                $this->session->unset_userdata('value_where');
                                $this->session->unset_userdata('where');
                                break;
                            default:
                                $this->session->set_userdata('where','category');
                                $this->session->set_userdata('value_where',$data);
                                $this->session->set_userdata('all_article',0);
                                break;                     
                        }
                    }
                    if($uri4='product'){
                        switch ($data){
                            case 'all':
                                $this->session->set_userdata('all_product',1);
                                $this->session->unset_userdata('value_where');
                                $this->session->unset_userdata('where');
                                break;
                            default:
                                $this->session->set_userdata('where','category');
                                $this->session->set_userdata('value_where',$data);
                                $this->session->set_userdata('all_product',0);
                                break;                     
                        }
                    }
                    break;
            }
        }
    }
    function xuly(){
        //$this->session->set_userdata('order',0);
        $this->rounte = $this->security->xss_clean($this->uri->segment(3,0));//su chu run
        $dk = $this->security->xss_clean($this->uri->segment(4,0)) ;//sau chu run
        $id = $this->security->xss_clean($this->uri->segment(5,0));//lay id
        $this->id = $id;
        if(!empty($_POST)){
            if($this->validate()){
                 $post_data=$_POST;
            }else{            
                 $dk='edit';            
            }    
        }
        if(empty($post_data)){$post_data='';}           
        $data['page'] = $this->run($dk,$id,$post_data);
        $data['setting'] = $this->Admin_model->get_one($this->tb_setting);
        $data['contact_new'] = $this->Admin_model->get_number($this->tb_lienhe,array('trangthai'=>0));
        if(empty($data['contact_new'])){
           $data['contact_old'] = $this->Admin_model->get_number($this->tb_lienhe,array('trangthai'=>1)); 
                 
        }        
        $this->load->view('admin/index',$data);
    }
    
    function run($dk,$id,$post_data=''){
        if(!is_numeric($id)){$id=0;}
        if(!empty($this->rounte)){$table= $this->rounte;$page=$this->rounte;}else $table='';//chua kiem tra co bang hay chua
        
        if(!empty($dk)){
            switch($dk){
                case 'list':
                    if(!empty($post_data)){
                        $data = $post_data;
                        $data = $this->xuly_dulieu($data,$table,$id);
                        if($id){
                            $this->db->where('id', $id);
                            $this->db->update($table, $data); 
                            $this->session->set_userdata('thongbao','Đã Sửa xong');
                        }else{
                            $this->db->insert($table, $data); 
                            $this->session->set_userdata('thongbao','Đã thêm');                            
                            
                        }
                        redirect(base_url().'admin/xuly/'.$page.'/list');
                    }
                    //hien thi danh sach
                    $this->base_url_trang = base_url().'admin/xuly/'.$page.'/list/';
                    if($table != $this->session->userdata('sec_table')){
                        //check xem co trung bang hay khong de kiem tra xem dang o trang cu hoac trang moi xoa session//bang ba
                        // bang bang session bang thi kiem tra order_by
                        $this->session->set_userdata('order',0);
                        $this->session->set_userdata('sec_table',$table);
                        $this->session->set_userdata('where',0);
                    }
                    if($this->session->userdata('order')){
                            $order = array('truong'=>$this->session->userdata('order'),'sapxep'=>$this->session->userdata('sapxep'));
                    }else $order=array();
                    
                     // limit start dung sau 
                    if(!$this->session->userdata('limit')){$this->session->set_userdata('limit',$this->limit);}else $this->limit = $this->session->userdata('limit');
                    $this->per_page = $this->limit;// so record tren 1 trang bang limit
                    if($id){
                        $start_limit = $id;
                    }else $start_limit=0;
                    if($this->session->userdata('change_cat')){
                        $start_limit=0;
                        $this->session->set_userdata('change_cat',0); 
                    }
                    $limit = $this->limit;
                    
                    //where
                    if($this->session->userdata('where')){
                        $where=$this->session->userdata('where');
                        $value=$this->session->userdata('value_where');
                        $where =array($where=>$value);
                    }else $where = array();
                    //
                    
                    $this->total_rows =$this->Admin_model->get_number($table,$where);
                    $this->phantrang(); 
                    //thong baohien so ket qua tren tong so record
                    $tt_limit = $this->limit +$id;
                    if($this->limit>=$this->total_rows){$total = $this->total_rows;}else $total =$tt_limit;
                    $result_mensenger = "danh sách từ $id - $total  của $this->total_rows";
                    
                    $cat = $this->cat($table);
                    $data =array('data'=>$this->Admin_model->get_data($table,$where,$order,$limit,$start_limit),'result_mensenger'=>$result_mensenger,'cat'=>$cat) ;                               
                    return $this->load->view('admin/content/'.$page.'_list',$data,true);//true la k hien chi tra ve
                    break;
                case 'edit':
                    $cat = $this->cat($table);
                    //hien thi sua
                    if($id){
                        $data =array('data'=>$this->Admin_model->get_one($table,array('id'=>$id)),'cat'=>$cat);                    
                    }else{
                        $data = array('cat'=>$cat);                    
                    }
                    return $this->load->view('admin/content/'.$page.'_edit',$data,true);//true la k hien chi tra ve
                    break;
                case 'xoa':
                   if($id){                    
                    $this->db->delete($table, array('id' => $id)); 
                    $this->session->set_userdata('thongbao','Đã thực hiện');
                    
                     redirect(base_url().'admin/xuly/'.$page.'/list');
                   }
                   break;
            }
        }
    }
    function xuly_dulieu($data,$table,$id=''){  
        if($table == 'users'){
            if(!empty($data['new_password_key']) && trim($data['new_password_key']) != ''){
                $data['password'] = sha1(md5($data['new_password_key']));
            }
        }
        if(!empty($data['metades'])){
            $data['metades'] = trim ($data['metades']);
        }
        if(!empty($data['metakey'])){
            $data['metakey']= trim($data['metakey']);
        }
        // danh muc san pham noi bat
        if($table=='product_category'){
            if(empty($data['highlights'])){
                $data['highlights']=0;
            }
        }
        // san pham noi bat ban chay tieu bieu
        if($table=='product'){
            if(empty($data['noibat'])){
                $data['noibat']=0;
            }
            
             if(empty($data['banchay'])){
                $data['banchay']=0;
            }
             if(empty($data['tieubieu'])){
                $data['tieubieu']=0;
            }
            // xu ly thuoc tinh san pham
            $tuychon= array();
            foreach ($this->Admin_model->get_data('option',array('publish'=>1)) as $option){                                
                      $kkey =  'tuychon_'.$option->id;
                      if(!empty($data[$kkey])){
                        $tuychon[] = $data[$kkey];
                        unset($data[$kkey]);
                      }      
            }
            if(!empty($tuychon)){
                sort( $tuychon );
                $data['option'] = implode ('%', $tuychon);
            }
            
        }
        // san pham
        if(($table=='article_category')||($table=='article')||($table=='product_category')||($table=='product')){
            if(empty($data['alias'])){
                $them=0;
                $data['alias']=creat_alias($data['title']);
            }else 
                $data['alias']=creat_alias($data['alias']);      
            $alias =$data['alias'];
            $alias2 =$data['alias'];                   
            $dieukien=1;
            while($dieukien){
                if(!empty($id)){$nd =array('alias'=>$alias,'id !='=>$id);}
                else $nd =array('alias'=>$alias);
                $check =$this->Admin_model->check_trung($nd,$table);  
                if($check){
                    $dieukien=$dieukien+1;
                    $alias = $alias2.$dieukien;               
                }else $dieukien=0;
            }           
            $data['alias']=$alias; 
            
            
            //xu ly bai viet            
            if($table== 'article'){
                if(empty($data['image'])){
                    $ddd = $data['fulltext'].'<img src="upload/default.jpg"/>';//'images/default.jpg'
                    $diachianh=laydiachianh($ddd);//lay dia chi anh
                    $data['image'] = $diachianh;
                }
                if(empty($data['introtext'])){
                    //character_limiter($row_baiviet->title,35);
                    //xu ly introtext
                    $loaibohtml=loaibo_html($data['fulltext']);//loai bo ma html       
                    $loaibohtml=word_limiter($loaibohtml, $this->sochu);// lay 30 chu
                    $loaibohtml=trim($loaibohtml);
                    $data['introtext']=$loaibohtml;
                    $data['fulltext']=loaibo_div_html($data['fulltext']);
                    if(empty($data['metades'])){
                        $data['metades']= $loaibohtml;
                    }  
                }
                
            }//en xu ly anh+ meta des bai viet
            
            /*xu ly anh san pham san pham            
            if($table== 'product'&&!empty($data['image'])){
               $image= $data['image'];
               $data['image'] = implode (',',$image);
            }
            en xu ly anh san pham
            */
            if(empty($data['metakey'])||empty($data['metades'])){
                $setting=$this->Admin_model->get_one('setting',array('id'=>1));
                if(empty($data['metakey'])){$data['metakey']=$setting->metakey;}
                if(empty($data['metades'])){$data['metades']=$setting->metades;}
            } 
        } 
        //en danh muc voi tin tuc       
        return $data;
    }
    ///////////////////////////
    function capnhat_slsanpham($dieuhuong='',$id_danhmuc){// cap nhat so luong san pham cho dnah muc(hancode)
        switch ($dieuhuong){
            case 'them':
            $dt = $this->Admin_model->get_data('product_category');
            foreach ($dt as $dt1){
                $mdt[$dt1->id]=$dt1;
            }
            $this->child_cat($id_danhmuc,$mdt);
            break;
            case 'xoa':
            $dt = $this->Admin_model->get_data('product_category');
            foreach ($dt as $dt1){
                $mdt[$dt1->id]=$dt1;
            }
            $this->child_cat_xoa($id_danhmuc,$mdt);
            break;
        }
    }
    function child_cat($id=0,$mdt){// lay danh muc con nho nhat 
        $data1 = $mdt[$id];
        $data1->total = $data1->total+1;
        $this->db->where('id',$data1->id);
        $this->db->update('product_category',$data1);
        if(!empty($data1->parentid)){
            $this->child_cat($data1->parentid,$mdt);
        }
         
    }
    function child_cat_xoa($id=0,$mdt){// lay danh muc con nho nhat 
        $data1 = $mdt[$id];
        $data1->total = $data1->total-1;
        $this->db->where('id',$data1->id);
        $this->db->update('product_category',$data1);
        if(!empty($data1->parentid)){
            $this->child_cat($data1->parentid,$mdt);
        }
         
    }
    ////////////////////////////   
    function cat($table){
        if($this->id){$where=array('id !='=>$this->id);}else $where='';
        switch ($table){
            case 'article_category':
              return $this->Admin_model->get_data($table,$where); 
              break;
            case 'article':
              return $this->Admin_model->get_data($this->tb_article_category);
              break;
            case 'product_category':
              return $this->Admin_model->get_data($table,$where); 
              break;
            case 'product':
              return $this->Admin_model->get_data($this->tb_product_category);
              break;
            case 'option_value':
              return $this->Admin_model->get_data('option');
              break;
            default:
              return true;
              break;
        }         
        
    }
    function validate(){
        
        switch($this->rounte){
        case 'hotro':
            $this->form_validation->set_rules('name','Tên','required|xss_clean|min_length[4]|max_length[20]');
            $this->form_validation->set_rules('yahoo','Yahoo','required|xss_clean|min_length[4]|max_length[30]');
            $this->form_validation->set_rules('mobile','Điện thoại','required|xss_clean|numeric|min_length[9]|max_length[12]'); 
            break;
        case 'article':
            $this->form_validation->set_rules('title','Tên danh mục','required|xss_clean|min_length[2]');
            $this->form_validation->set_rules('noibat','nổi bật','numeric');
            break;
        case 'product':
            $this->form_validation->set_rules('title','Tên sản phẩm','required|xss_clean|min_length[2]');
            break;
        case 'article_category':
            $this->form_validation->set_rules('title','Tên danh mục','required|xss_clean|min_length[2]');
            $this->form_validation->set_rules('publish','Hiển thị','required|numeric');
            break;
        default:
        return true;
                   
        }
        if($this->form_validation->run()==true){
            return true;
        }else return false;
    }
    function phantrang(){
        $this->load->library('pagination');
        $config['base_url'] = $this->base_url_trang;
        $config['total_rows'] = $this->total_rows;
        $config['per_page'] = $this->per_page;
        $config['uri_segment'] = 5;
        $config['num_links'] = 10;
        $config['first_link'] = '<<';
        $config['first_tag_open'] = '<li class="firt_pag">';//div cho chu <<
        $config['first_tag_close'] = '</li>';//div cho chu <<
        $config['last_link'] = '>>';
        $config['last_tag_open'] = '<li class="last_pag">';
        $config['last_tag_close'] = '</li>';
        //-------next-
        $config['next_link'] = 'next &gt;';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        //------------preview
        $config['prev_link'] = '&lt; prev';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
       // ------------------cu?npage
        $config['cur_tag_open'] = '<li class="current">';
        $config['cur_tag_close'] = '</li>';
        //--so 
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        //-----
        $this->pagination->initialize($config);
    
    } 
    function logout(){
        $this->session->unset_userdata('id');
        $this->session->unset_userdata('logedin');
        redirect('dangnhap');
    }
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */